/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package com.pb.diplom.first.business;

import com.pb.diplom.first.dao.CategoryDao;
import com.pb.diplom.first.dao.CategoryJoinDao;
import com.pb.diplom.first.dbProp.DbProperties;
import com.pb.diplom.first.tables.Category;
import com.pb.diplom.first.tables.CategoryJoin;
import java.sql.SQLException;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 *
 * @author Slava
 */
public class DBStorageCategory {

    private final static DBStorageCategory instance = new DBStorageCategory();
    private final Map<Long, CategoryJoin> category = new HashMap<>();
    Category categories = new Category();
    CategoryJoin cat = new CategoryJoin();
    CategoryJoinDao dao = new CategoryJoinDao(DbProperties.LOGIN, DbProperties.PASSWORD, DbProperties.URL);

    private DBStorageCategory() {
        init();
    }

    public static DBStorageCategory getInstance() {
        return instance;
    }

    private void init() {
        List<CategoryJoin> ct = dao.getAll();
        for (CategoryJoin cat : ct) {
            category.put(cat.getId(), new CategoryJoin(cat.getId(), cat.getName(), cat.getParent()));
        }
    }

    public CategoryJoin saveOrUpdate(CategoryJoin category) throws SQLException {
        dao.save(category);
        //sleep(1000);
        CategoryJoin item = cat.getId() != null
                ? category : new CategoryJoin(dao.getId(cat), cat.getName(), cat.getParent());
        this.category.put(dao.getId(item), item);
        return item;
    }

    public Collection<CategoryJoin> getCategories() {
        return category.values();
    }

    public Object[][] getCategoriesAsTable() throws SQLException {
        Object[][] result = new Object[category.size()][3];
        int index = 0;
        for (CategoryJoin cat : dao.getAll()) {
            result[index][0] = cat.getId();
            result[index][1] = cat.getName();
            result[index][2] = cat.getParent();
            index++;
        }
        return result;
    }

}
